package club.janna.concurrency.example.atomic;

import club.janna.concurrency.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 使用atomic包中的AtomicBoolean，确保某段代码只被执行一次
 * @Auther: guopanbo
 * @Date: 2018/7/21 23:41
 * @Description:
 */
@Slf4j
@ThreadSafe
public class AtomicExample4 {

    /**
     *  请求总数
     */
    private static final int CLIENT_TOTAL = 10_000_000;
    /**
     * 开始竞争的计数
     */
    private static final int START = 6_000_000;
    /**
     * 并发的线程总数
     */
    private static final int THREAD_TOTAL = 200_000;
    /**
     * 是否被执行过
     */
    private static AtomicBoolean hasExecuted = new AtomicBoolean(false);
    private static CountDownLatch countDownLatch = new CountDownLatch(CLIENT_TOTAL);
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(THREAD_TOTAL);
        for(int i = 0; i < CLIENT_TOTAL; i ++)
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                exe();
                semaphore.release();
                countDownLatch.countDown();
            });
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        log.info("hasExecute?  {}", hasExecuted.get());
    }

    private static void exe() {
        if(countDownLatch.getCount() < START && hasExecuted.compareAndSet(false, true)) {
            log.info("execute");
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
